package com.groupbuying.customer.service.impl;

import com.groupbuying.customer.connector.CurrencyFeign;
import com.groupbuying.customer.connector.SysconfigFeign;
import com.groupbuying.customer.constants.CommonConstants;
import com.groupbuying.customer.constants.CustomerUshopSearchConstants;
import com.groupbuying.customer.context.FilterContextHandler;
import com.groupbuying.customer.dao.CustomerDao;
import com.groupbuying.customer.dao.CustomerUshopDao;
import com.groupbuying.customer.domain.CustomerAccountDO;
import com.groupbuying.customer.domain.CustomerDO;
import com.groupbuying.customer.domain.CustomerUshopDO;
import com.groupbuying.customer.dto.CustomerInfoApiDTO;
import com.groupbuying.customer.pojo.CustomerInfoEnum;
import com.groupbuying.customer.service.CustomerAccountService;
import com.groupbuying.customer.service.CustomerService;
import com.groupbuying.customer.utils.ChineseCharacters2PinyinUtils;
import com.groupbuying.customer.utils.DateFormatHelper;
import com.groupbuying.customer.utils.apiresult.ApiResult;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.groupbuying.customer.dao.CustomerInfoDao;
import com.groupbuying.customer.domain.CustomerInfoDO;
import com.groupbuying.customer.service.CustomerInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


@Service
public class CustomerInfoServiceImpl implements CustomerInfoService {
	private static final Logger logger = LoggerFactory.getLogger(CustomerInfoServiceImpl.class);
	@Autowired
	private CustomerInfoDao customerInfoDao;

	@Autowired
	private CustomerDao customerDao;

	@Autowired
	private CurrencyFeign currencyFeign;

	@Autowired
	private SysconfigFeign sysconfigFeign;

	@Autowired
	private CustomerUshopDao customerUshopDao;

	@Autowired
	private CustomerAccountService customerAccountService;
	
	@Override
	public CustomerInfoDO get(String uuid){
		return customerInfoDao.get(uuid);
	}
	
	@Override
	public List<CustomerInfoDO> list(Map<String, Object> map){
		return customerInfoDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return customerInfoDao.count(map);
	}
	
	@Override
	public int save(CustomerInfoDO info){
		return customerInfoDao.save(info);
	}
	
	@Override
	public int update(CustomerInfoDO info){
		return customerInfoDao.update(info);
	}
	
	@Override
	public int remove(String uuid){
		return customerInfoDao.remove(uuid);
	}
	
	@Override
	public int batchRemove(String[] uuids){
		return customerInfoDao.batchRemove(uuids);
	}

    @Override
    public String addPinyinCustomerInfo(CustomerDO customer, MultipartFile[] imgFiles) {
		CustomerInfoDO customerInfoDO = new CustomerInfoDO();
		customerInfoDO.setUuid(sysconfigFeign.getUuidByLeaf());
		customerInfoDO.setDelflag(CommonConstants.COMMON_FLAG_UNDEL);
		customerInfoDO.setOpetime(DateFormatHelper.getNowTimeStr());
		customerInfoDO.setCustomeruuid(customer.getUuid());
		customerInfoDO.setNickname(customer.getCustomername());
		customerInfoDO.setCreateopetime(DateFormatHelper.getNowTimeStr());
		customerInfoDO.setVersion(0);
		// M mFile = this.uploadImage1_P4(m, imgFiles);
		// 设置头像
		customerInfoDO.setImage("");
		// 设置拼音名字相关
		this.setPinyinName(customerInfoDO);
		this.save(customerInfoDO);
		return customerInfoDO.getUuid();
    }

	public void setPinyinName(CustomerInfoDO customerInfo){
		String name = customerInfo.getNickname();
		if(StringUtils.isNotBlank(name)){
			String pinyinName = ChineseCharacters2PinyinUtils.toHanyuPinyin(name);
			customerInfo.setPinyinnickname(pinyinName.toLowerCase());
			String first = pinyinName.substring(0, 1);
			String first1 = first;
			if (first.matches("[a-zA-Z]+")) {
				first1 = first.toUpperCase();
			}else{
				first1 = CustomerInfoEnum.NON_LETTERS;
			}
			customerInfo.setPinyinfirstletter(first1);
		}else{
			customerInfo.setPinyinfirstletter(CustomerInfoEnum.NON_LETTERS);
		}
	}

	@Override
	public ApiResult getCustomer(String customerId){
		//查询用户信息
		CustomerUshopDO customerUshopDO = customerUshopDao.get(customerId);
		if(null == customerUshopDO){
			return ApiResult.failure();
		}else{
			return ApiResult.success(customerUshopDO);
		}
	}

	@Override
	@Transactional
	public ApiResult getUserInfo(Map<String, Object> mapParams){
		// 解析map参数
		String userId = FilterContextHandler.getUserID();
		if(StringUtils.isEmpty(userId)){
			userId = (String) mapParams.get("customerId");
		}
		//查询用户信息
		CustomerUshopDO customerUshopDO = customerUshopDao.get(userId);

		//根据会员,查找主库
		CustomerAccountDO customerAccountDO = customerAccountService.getByCustomerUuid(customerUshopDO.getMainUuid());;
		//查找用户主表
		CustomerDO customerDO = customerDao.get(customerUshopDO.getMainUuid());
		// 查询积分账户
		Map currencyMap = new HashMap();
		currencyMap.put("customerId", customerUshopDO.getCustomerId());
		currencyMap.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
		Map res = currencyFeign.getCurrencyAccount(currencyMap);
//		if (res == null) {
//			logger.info("查询积分账户为空，准备创建积分账户，用户ID：{}",customerUshopDO.getCustomerId());
//			if(!"".equals(customerDO.getMobile()) && null == customerDO.getMobile()){
//				// 创建积分账户
//				Map searchMap = new HashMap();
//				searchMap.put(CustomerUshopSearchConstants.SEARCH_CUSTOMERID, customerUshopDO.getCustomerId());
//				res = currencyFeign.createCurrencyCustomer(searchMap);
//				logger.info("创建账户完成,用户ID:{},积分账户：{}", customerUshopDO.getCustomerId(),res.get("useCurrency"));
//			}else{
//				logger.error("该用户：{} 没有手机号:{} ,创建积分账户失败",customerUshopDO.getCustomerId(),customerDO.getMobile());
//			}
//		}
		CustomerInfoApiDTO customerInfoApiDTO = new CustomerInfoApiDTO();
		customerInfoApiDTO.setCustomerId(userId);
		if (res == null){
			customerInfoApiDTO.setCurrencyNumber(new BigDecimal("0"));
		}else{
			customerInfoApiDTO.setCurrencyNumber(new BigDecimal(res.get("useCurrency").toString()));
		}
		if (res.get("password") == null) {
			//未设置积分支付密码
			customerInfoApiDTO.setIsCurrencyPayWord("0");
		} else {
			//已设置积分支付密码
			customerInfoApiDTO.setIsCurrencyPayWord("1");
		}
		customerInfoApiDTO.setNickName(customerUshopDO.getMobile());
		customerInfoApiDTO.setMobile(customerUshopDO.getMobile());
		if(null == customerAccountDO){
			customerInfoApiDTO.setAccountBalance(Double.valueOf("0.00"));
		} else {
			customerInfoApiDTO.setAccountBalance(customerAccountDO.getNoaccountbalance());
		}
		if (null != customerDO){
			customerInfoApiDTO.setGymobile(customerDO.getMobile());
		}
		return ApiResult.success(customerInfoApiDTO);
	}
}
